package cn.edu.gzhu.workOrderManagement.intercepter;

import cn.edu.gzhu.workOrderManagement.constants.UserConstant;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 这是一个授权拦截器只拦截 /user/listUsers 路径的请求,位于拦截器链的第二位
 * @author chen xi
 */
@Component
@Slf4j
public class ListUserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到用户查询请求");
        String queryOrganization = request.getParameter("organization");
        Claims claims =(Claims) request.getAttribute("claims");

        //普通用户不能调用这个接口
        if (claims.get("authority").equals(UserConstant.COMMON_USER)){
            log.info("普通用户被拒绝");
            response.setStatus(401);
            return false;
        }
        //组织负责人不能查看本组织以外的用户
        if (!claims.get("organization").equals(queryOrganization)&&((Integer)claims.get("authority")).equals(UserConstant.SUPERINTENDENT)){
            log.info("组织负责人被拒绝");
            response.setStatus(401);
            return false;
        }
        log.info("放行");
        return true;
    }
}
